<?php
/**
 * Created by PhpStorm.
 * User: zhenl
 * Date: 2022/10/21
 * Time: 10:27
 */

namespace app\api\controller;


use app\BaseController;
use app\Request;
use common\models\UserModel;
use EasyWeChat\Factory;
use Firebase\JWT\JWT;


class Auth extends BaseController
{
    /**
     * 随机验证码
     *
     * @var string
     */
    private $code = '8888';

    /**
     * 手机号注册功能
     *
     * @param Request $request
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function mobileRegister(Request $request)
    {
        // 数据获取 Start
        $post = $request->post();
        // 数据获取 End
        // 数据验证 Start
        if (empty($post['mobile']) ||
            empty($post['password']) ||
            empty($post['confirm_password']) ||
            empty($post['code'])
        ) {
            return json([
                'code' => 1,
                'msg' => '请输入完成内容',
                'data' => []
            ]);
        }
        // 判断验证码
        if ($post['code'] != $this->code) {
            return json([
                'code' => 1,
                'msg' => '验证码错误',
                'data' => []
            ]);
        }
//        if ($post['code'] != cache("code-{$post['mobile']}-1")) {
//            return json([
//                'code' => 1,
//                'msg' => '验证码错误',
//                'data' => []
//            ]);
//        }
        if ($post['password'] != $post['confirm_password']) {
            return json([
                'code' => 1,
                'msg' => '两次密码输入不一致',
                'data' => []
            ]);
        }
        $user_model = UserModel::where('mobile', $post['mobile'])->find();
        if (!empty($user_model)) {
            return json([
                'code' => 1,
                'msg' => '手机号已注册',
                'data' => []
            ]);
        }
        // 黑名单
//        $black_list = ['15605009999'];
//        if(in_array($post['mobile'], $black_list)) {
//            return json([
//                'code' => 1,
//                'msg' => '当前手机号不可注册',
//                'data' => []
//            ]);
//        }
        // 数据验证 End

        $data = $post;
        $data['salt'] = rand(1000, 9999);
        $data['password'] = md5($data['password'] . $data['salt']);
        $user_model = UserModel::create($data);

        return json([
            'code' => 0,
            'msg' => '成功',
            'data' => $user_model->id
        ]);
    }


    public function mobileLogin(Request $request)
    {
        // 数据获取 Start
        $post = $request->param();
        // 数据获取 End
        // 数据验证 Start
        if (!$post['mobile']) {
            return json([
                'code' => 1,
                'msg' => '请填写手机号',
                'data' => []
            ]);
        }
        $user_model = UserModel::where('mobile', $post['mobile'])->find();
        if (!$user_model) {
            return json([
                'code' => 1,
                'msg' => '用户不存在',
                'data' => []
            ]);
        }
        if ($user_model->status == 0) {
            return json([
                'code' => 1,
                'msg' => '用户被禁用',
                'data' => []
            ]);
        }
        if (md5($post['password'] . $user_model->salt) != $user_model->password) {
            return json([
                'code' => 1,
                'msg' => '密码错误',
                'data' => []
            ]);
        }
        // 判断验证码
        if ($post['code'] != $this->code) {
            return json([
                'code' => 1,
                'msg' => '验证码错误',
                'data' => []
            ]);
        }
        // 数据验证 End

        //返回用户信息
        return json([
            'code' => 0,
            'msg' => '成功',
            'data' => $user_model->hidden([
                'create_time', 'update_time', 'delete_time',
                'openid', 'session_key',
                'password', 'salt'
            ])
        ]);
    }


    /**
     * 通过CODE换OPENID登录
     *
     * @param Request $request
     * @return mixed
     */
    public function login(Request $request)
    {
        $code = $request->param('code');

        $app = Factory::miniProgram(config('wx'));

        $info = $app->auth->session($code);
        if ($info['errcode'] > 0) {
            throw new Exception($info['errmsg'], $info['errcode']);
        }
        $user = UserModel::where('openid', $info['openid'])->find();
        if ($user) {
            $user->save([
                'openid' => $info['openid'],
                'session_key' => $info['session_key'],
//                'last_login_time' => time()
            ]);
        } else {
            $user = UserModel::create([
                'openid' => $info['openid'],
                'session_key' => $info['session_key'],
//                'last_login_time' => time()
            ]);
        }

        $params = [
            'iss' => config('app.app_host'),
            'iat' => time(),
            'nbf' => time(),
            'exp' => strtotime('+ 1 weeks'),
            'jti' => [
                'id' => $user->id
            ]
        ];
        $token = JWT::encode($params, config('app.jwt_key'));
        $expire_time = strtotime('+ 72 hours');
        $user = UserModel::find($user->id)->hidden(['create_time', 'update_time', 'delete_time', 'openid', 'session_key', 'memo']);

        return $this->success(compact('token', 'expire_time', 'user'));
    }
}